<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" v-if="useUserStore().isUser">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="房屋信息" prop="houseId">
          <el-select
            v-model="queryParams.houseId"
            placeholder="请选择房屋"
            clearable
            filterable
            remote
            :remote-method="handleHouseSearch"
            :loading="houseSearchLoading"
            style="width: 250px"
          >
            <el-option
              v-for="item in houseOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态" prop="isPaid">
          <el-select
            style="width: 200px"
            v-model="queryParams.isPaid"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="未缴费" :value="false" />
            <el-option label="已缴费" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期时间" prop="dueDate">
          <el-date-picker
            v-model="queryParams.dueDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <span>物业费列表</span>
            <el-button
              v-if="userInfo.role === 'Admin'"
              type="primary"
              :icon="Plus"
              @click="handleAdd"
              style="margin-left: 20px"
              >新增收费</el-button
            >
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="feeList" border style="width: 100%">
        <el-table-column label="房屋信息" min-width="180">
          <template #default="{ row }">
            {{ `${row.buildingNo}栋${row.unitNo}单元${row.roomNo}室` }}
          </template>
        </el-table-column>
        <el-table-column
          label="业主信息"
          min-width="150"
          v-if="useUserStore().isAdmin"
        >
          <template #default="{ row }">
            {{ row.ownerName }}
            <el-tag size="small" type="info" class="ml-2">
              {{ row.ownerPhone }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          label="费用金额"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            {{ row.amount.toFixed(2) }}元
          </template>
        </el-table-column>
        <el-table-column
          prop="dueDate"
          label="到期时间"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDate(row.dueDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="isPaid"
          label="缴费状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.isPaid ? 'success' : 'danger'">
              {{ row.isPaid ? "已缴费" : "未缴费" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!row.isPaid"
              type="primary"
              link
              :icon="Check"
              @click="handlePayment(row)"
            >
              确认缴费
            </el-button>
            <el-button
              v-if="userInfo.role === 'Admin' && !row.isPaid"
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout=" prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/批量生成对话框 -->
    <el-dialog
      v-if="userInfo.role === 'Admin'"
      v-model="dialog.visible"
      :title="dialog.type === 'single' ? '新增物业费' : '批量生成物业费'"
      width="500px"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialog.form"
        :rules="dialog.rules"
        label-width="100px"
      >
        <template v-if="dialog.type === 'single'">
          <el-form-item label="房屋" prop="houseId">
            <el-select
              v-model="dialog.form.houseId"
              placeholder="请选择房屋"
              filterable
              remote
              :remote-method="handleHouseSearch"
              :loading="houseSearchLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in houseOptions"
                :key="item.id"
                :label="item.address"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="房屋状态" prop="houseStatus">
            <el-select
              v-model="dialog.form.houseStatus"
              placeholder="请选择房屋状态"
              multiple
              style="width: 100%"
            >
              <el-option label="已入住" value="Occupied" />
              <el-option label="已出租" value="Rented" />
              <el-option label="已售出" value="Sold" />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="费用金额" prop="amount">
          <el-input-number
            v-model="dialog.form.amount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          >
            <template #append>元</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="到期时间" prop="dueDate">
          <el-date-picker
            v-model="dialog.form.dueDate"
            type="date"
            placeholder="选择到期时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认缴费对话框 -->
    <el-dialog v-model="paymentDialog.visible" title="确认缴费" width="400px">
      <div class="payment-info">
        <p>房屋信息：{{ paymentDialog.data?.house?.address }}</p>
        <p>业主信息：{{ paymentDialog.data?.house?.owner?.name }}</p>
        <p>费用金额：{{ paymentDialog.data?.amount?.toFixed(2) }}元</p>
        <p>到期时间：{{ formatDate(paymentDialog.data?.dueDate) }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment">确认缴费</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Check,
  Delete,
  Upload,
  Printer,
} from "@element-plus/icons-vue";
import {
  getPropertyFees,
  createPropertyFee,
  updatePaymentStatus,
  deletePropertyFee,
} from "@/api/property";
import { getHouses } from "@/api/house";
import { useUserStore } from "@/stores/user";

// 查询参数
const queryParams = ref({
  houseId: "",
  isPaid: "",
  dueDateStart: "",
  dueDateEnd: "",
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const feeList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 统计数据
const statistics = ref({
  unpaidAmount: 0,
  paidAmount: 0,
  paymentRate: 0,
});

// 房屋选择相关
const houseSearchLoading = ref(false);
const houseOptions = ref([]);

// 对话框相关
const dialog = reactive({
  visible: false,
  type: "single", // single or batch
  form: {
    houseId: "",
    houseStatus: [],
    amount: 0,
    dueDate: "",
  },
  rules: {
    houseId: [{ required: true, message: "请选择房屋", trigger: "change" }],
    houseStatus: [
      { required: true, message: "请选择房屋状态", trigger: "change" },
    ],
    amount: [{ required: true, message: "请输入费用金额", trigger: "blur" }],
    dueDate: [{ required: true, message: "请选择到期时间", trigger: "change" }],
  },
});

// 缴费对话框
const paymentDialog = reactive({
  visible: false,
  data: null,
});

// 用户信息
const userInfo = ref({
  username: "",
  role: "",
});

// 获取用户信息
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    userInfo.value = JSON.parse(userInfoStr);
  }
});

// 获取物业费列表
const getList = async () => {
  try {
    loading.value = true;
    const [dueDateStart, dueDateEnd] = queryParams.value.dueDate || [];
    const params = {
      ...queryParams.value,
      dueDateStart,
      dueDateEnd,
    };
    delete params.dueDate;

    const res = await getPropertyFees(params);
    feeList.value = res.items;
    total.value = res.total;

    // 更新统计数据
    updateStatistics();
  } catch (error) {
    console.error("获取物业费列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStatistics = () => {
  const currentMonth = new Date().getMonth();
  const currentMonthFees = feeList.value.filter((fee) => {
    const feeMonth = new Date(fee.dueDate).getMonth();
    return feeMonth === currentMonth;
  });

  const unpaidAmount = currentMonthFees
    .filter((fee) => !fee.isPaid)
    .reduce((sum, fee) => sum + fee.amount, 0);

  const paidAmount = currentMonthFees
    .filter((fee) => fee.isPaid)
    .reduce((sum, fee) => sum + fee.amount, 0);

  const total = unpaidAmount + paidAmount;
  const paymentRate = total > 0 ? (paidAmount / total) * 100 : 0;

  statistics.value = {
    unpaidAmount,
    paidAmount,
    paymentRate,
  };
};

// 搜索房屋
const handleHouseSearch = async (query) => {
  if (query) {
    try {
      houseSearchLoading.value = true;
      const res = await getHouses({
        keyword: query,
        pageSize: 10,
      });
      houseOptions.value = res.items.map((house) => ({
        id: house.id,
        address: `${house.buildingNo}栋${house.unitNo}单元${house.roomNo}室`,
      }));
    } catch (error) {
      console.error("搜索房屋失败：", error);
    } finally {
      houseSearchLoading.value = false;
    }
  } else {
    houseOptions.value = [];
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增物业费
const handleAdd = () => {
  dialog.type = "single";
  dialog.form = {
    houseId: "",
    amount: 0,
    dueDate: "",
  };
  dialog.visible = true;
};

// 批量生成
const handleBatchAdd = () => {
  dialog.type = "batch";
  dialog.form = {
    houseStatus: [],
    amount: 0,
    dueDate: "",
  };
  dialog.visible = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialog.type === "single") {
      await createPropertyFee(dialog.form);
      ElMessage.success("创建成功");
    } else {
      await createPropertyFee({
        ...dialog.form,
        isBatch: true,
      });
      ElMessage.success("批量生成成功");
    }
    dialog.visible = false;
    getList();
  } catch (error) {
    console.error("保存失败：", error);
  }
};

// 确认缴费
const handlePayment = (row) => {
  paymentDialog.data = row;
  paymentDialog.visible = true;
};

// 确认缴费提交
const confirmPayment = async () => {
  try {
    await updatePaymentStatus(paymentDialog.data.id, { isPaid: true });
    ElMessage.success("缴费成功");
    paymentDialog.visible = false;
    getList();
  } catch (error) {
    console.error("缴费失败：", error);
  }
};

// 删除物业费
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该物业费记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deletePropertyFee(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 打印功能
const handlePrint = (row) => {
  ElMessage.info("打印功能开发中");
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .right {
        display: flex;
        align-items: center;
        gap: 20px;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .payment-info {
    p {
      margin: 10px 0;
      font-size: 14px;
    }
  }

  .ml-2 {
    margin-left: 8px;
  }
}
</style>
